﻿using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraTab;
using DevExpress.XtraTab.ViewInfo;
using OznerOA.BLL;
using OznerOA.Common;
using OznerOA.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace OznerOA.UI
{
    public partial class FrmMain : FrmBase
    {

        private UserBLL userBLL = UserBLL.GetInstance();
        //保存所有的日志
        private List<Log> AllLogs = new List<Log>();
        #region 构造方法
        public FrmMain() : base()
        {
            loadSkin();
            SplashScreenManager.ShowForm(typeof(FrmSplashScreen));
            InitializeComponent();
            this.Load += FrmMain_Load;
            SplashScreenManager.CloseForm();
            StartConsoleThread();
        }
        #endregion
        #region 事件
        #region 窗体加载事件
        private void FrmMain_Load(object sender, EventArgs e)
        {
            //设置菜单栏最小化
            ribbonControl1.Minimized = true;
            bbiBindWechat.ImageOptions.LargeImage = Properties.Resources.weixinlogo;
            //显示系统名
            this.Text = ConfigModel.SystemName;
            logBLL.Debug("系统名称:{0}", ConfigModel.SystemName);
            //初始化视图显示
            initViewShow();
            //显示登录对话框
            ShowLoginForm(true, null);
            //显示首页
            base.TabControlAddPageForm(tabMain, "首页", new FrmIndex());
            //控制台按钮选中状态设置
            btnShowInfo.Checked = ((int)LogType.INFO & ConfigModel.ConsoleShowType) == (int)LogType.INFO;
            btnShowWarn.Checked = ((int)LogType.WARN & ConfigModel.ConsoleShowType) == (int)LogType.WARN;
            btnShowDebug.Checked = ((int)LogType.DEBUG & ConfigModel.ConsoleShowType) == (int)LogType.DEBUG;
            btnShowError.Checked = ((int)LogType.ERROR & ConfigModel.ConsoleShowType) == (int)LogType.ERROR;
            //控制台按钮选中状态改变事件注册
            btnShowInfo.CheckedChanged += btnShowInfo_CheckedChanged;
            btnShowWarn.CheckedChanged += btnShowWarn_CheckedChanged;
            btnShowDebug.CheckedChanged += btnShowDebug_CheckedChanged;
            btnShowError.CheckedChanged += btnShowError_CheckedChanged;
        }
        #endregion
        #region 皮肤项点击事件
        private void skinRibbonGalleryBarItem1_GalleryItemClick(object sender, DevExpress.XtraBars.Ribbon.GalleryItemClickEventArgs e)
        {
            logBLL.Info("修改皮肤为:{0}", e.Item.Caption);
            ConfigModel.THEME = e.Item.Caption;
        }
        #endregion
        #region TabControl SizeChanged
        private void tabMain_SizeChanged(object sender, EventArgs e)
        {
            //将tabcontrol中的窗体控件重新最大化
            foreach (XtraTabPage tp in tabMain.TabPages)
            {
                if (tp.Controls.Count > 0 && tp.Controls[0] is FrmBase)
                {
                    FrmBase frm = tp.Controls[0] as FrmBase;
                    frm.WindowState = FormWindowState.Normal;
                    frm.WindowState = FormWindowState.Maximized;
                }
            }
        }
        #endregion
        #region 切换账号
        private void bbiChangeAccount_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowLoginForm(false, string.Empty);
        }
        #endregion
        #region 退出按钮点击事件
        private void bbiExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }
        #endregion
        #region 手风琴菜单菜单项点击事件
        private void accMenu_ElementClick(object sender, ElementClickEventArgs e)
        {
            if (e.Element.Style == ElementStyle.Item)
            {
                HttpAddress ha = ParseAddress(e.Element.Tag.ToString());
                //构建Form的完全限定名
                string type = e.Element.Tag.ToString();
                logBLL.Debug(type);

                try
                {
                    //反射创建Form对象
                    object z = Activator.CreateInstance(Type.GetType(type));
                    FrmBase frm = z as FrmBase;
                    //添加Page页
                    TabControlAddPageForm(tabMain, e.Element.Text, frm);
                }
                catch (Exception ex)
                {
                    logBLL.Error(ex.GetType().FullName + ":" + ex.Message + "\r\n" + ex.StackTrace);
                    BoxHelper.Info("功能尚未实现，敬请期待!");
                }
            }
        }
        #endregion
        #region TabControl的关闭按钮点击事件
        private void tabMain_CloseButtonClick(object sender, EventArgs ev)
        {
            if (ev is ClosePageButtonEventArgs)
            {
                ClosePageButtonEventArgs e = ev as ClosePageButtonEventArgs;
                if (e.Page.Text != "首页")
                {
                    logBLL.Debug("关闭Tab页:{0}", e.Page.Text);
                    tabMain.TabPages.Remove((XtraTabPage)e.Page);
                }
                else
                {
                    BoxHelper.Alert(this, "提示", "首页不能被关闭!");
                }
            }
        }
        #endregion
        #region 视图导航菜单项点击
        private void bciMenu_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (e.Item is BarCheckItem)
            {
                BarCheckItem item = e.Item as BarCheckItem;
                panelMenu.Visibility = item.Checked ? DevExpress.XtraBars.Docking.DockVisibility.Visible : DevExpress.XtraBars.Docking.DockVisibility.Hidden;
            }
        }
        #endregion
        #region 视图控制台项点击
        private void bciConsole_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            if (e.Item is BarCheckItem)
            {
                BarCheckItem item = e.Item as BarCheckItem;
                panelConsole.Visibility = item.Checked ? DevExpress.XtraBars.Docking.DockVisibility.Visible : DevExpress.XtraBars.Docking.DockVisibility.Hidden;
            }
        }
        #endregion
        #region 菜单面板Visibility属性改变
        private void panelMenu_VisibilityChanged(object sender, DevExpress.XtraBars.Docking.VisibilityChangedEventArgs e)
        {
            if (e.Visibility == DevExpress.XtraBars.Docking.DockVisibility.Visible)
            {
                logBLL.Debug("导航菜单面板:显示");
                ConfigModel.SHOW_MENU = "DOCK";
            }
            if (e.Visibility == DevExpress.XtraBars.Docking.DockVisibility.AutoHide)
            {
                logBLL.Debug("导航菜单面板:自动隐藏");
                ConfigModel.SHOW_MENU = "UNDOCK";
            }
            if (e.Visibility == DevExpress.XtraBars.Docking.DockVisibility.Hidden)
            {
                logBLL.Debug("导航菜单面板:隐藏");
                ConfigModel.SHOW_MENU = "HIDE";
            }
        }
        #endregion
        #region 菜单面板Visibility属性改变
        private void panelConsole_VisibilityChanged(object sender, DevExpress.XtraBars.Docking.VisibilityChangedEventArgs e)
        {
            if (e.Visibility == DevExpress.XtraBars.Docking.DockVisibility.Visible)
            {
                logBLL.Debug("控制台面板:显示");
                ConfigModel.SHOW_CONSOLE = "DOCK";
            }
            if (e.Visibility == DevExpress.XtraBars.Docking.DockVisibility.AutoHide)
            {
                logBLL.Debug("控制台面板:自动隐藏");
                ConfigModel.SHOW_CONSOLE = "UNDOCK";
            }
            if (e.Visibility == DevExpress.XtraBars.Docking.DockVisibility.Hidden)
            {
                logBLL.Debug("控制台面板:隐藏");
                ConfigModel.SHOW_CONSOLE = "HIDE";
            }
        }
        #endregion
        #region 绑定微信菜单点击
        private void bbiBindWechat_ItemClick(object sender, ItemClickEventArgs e)
        {
            FrmBindWechatApi frm = new FrmBindWechatApi();
            frm.ShowDialog(this);
        }
        #endregion
        #region 窗体关闭
        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            ShowWaiting("正在关闭程序...");
            WechatBLLAPI.GetInstance().logout();
            ThreadHelper.AbortAllThread();
            CloseWaiting();
        }
        #endregion
        #region 显示信息按钮点击
        private void btnShowInfo_CheckedChanged(object sender, EventArgs e)
        {
            if (btnShowInfo.Checked)
            {
                ConfigModel.ConsoleShowType += (int)LogType.INFO;
            }
            else
            {
                ConfigModel.ConsoleShowType -= (int)LogType.INFO;
            }
            reShowConsole = true;
        }
        #endregion
        #region 显示警告按钮点击
        private void btnShowWarn_CheckedChanged(object sender, EventArgs e)
        {
            if (btnShowWarn.Checked)
            {
                ConfigModel.ConsoleShowType += (int)LogType.WARN;
            }
            else
            {
                ConfigModel.ConsoleShowType -= (int)LogType.WARN;
            }
            reShowConsole = true;
        }
        #endregion
        #region 显示调试信息按钮点击
        private void btnShowDebug_CheckedChanged(object sender, EventArgs e)
        {
            if (btnShowDebug.Checked)
            {
                ConfigModel.ConsoleShowType += (int)LogType.DEBUG;
            }
            else
            {
                ConfigModel.ConsoleShowType -= (int)LogType.DEBUG;
            }
            reShowConsole = true;
        }
        #endregion
        #region 显示错误按钮点击
        private void btnShowError_CheckedChanged(object sender, EventArgs e)
        {
            if (btnShowError.Checked)
            {
                ConfigModel.ConsoleShowType += (int)LogType.ERROR;
            }
            else
            {
                ConfigModel.ConsoleShowType -= (int)LogType.ERROR;
            }
            reShowConsole = true;
        }
        #endregion
        #region 清空按钮点击
        private void btnClearConsole_Click(object sender, EventArgs e)
        {
            txtConsole.Text = "";
            AllLogs.Clear();
        }
        #endregion
        #endregion
        #region 显示登录窗体
        protected override void ShowLoginForm(bool EnableAutoLogin, string tip)
        {
            FrmLogin frm = new FrmLogin(EnableAutoLogin);
            if (!string.IsNullOrEmpty(tip)) frm.ErrorTip = tip;
            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                bsiLoginUserName.Caption = userBLL.LoginUser.Name;
            }
            else
            {
                //切换账号不需要关闭窗口
                if (EnableAutoLogin)
                    this.Close();
            }
        }
        #endregion
        #region 皮肤加载
        private void loadSkin()
        {
            string skinName = ConfigModel.THEME;
            logBLL.Debug("加载皮肤:{0}", skinName);
            if (!string.IsNullOrEmpty(skinName))
            {
                DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = skinName;
            }
        }
        #endregion
        #region 初始化视图显示
        private void initViewShow()
        {
            string ShowMenu = ConfigModel.SHOW_MENU;
            string ShowConsole = ConfigModel.SHOW_CONSOLE;
            SetDockPanelDock(panelMenu, bciMenu, ShowMenu, "菜单面板");
            SetDockPanelDock(panelConsole, bciConsole, ShowConsole, "控制台面板");
        }
        #endregion



        #region 控制台显示
        private void StartConsoleThread()
        {
            ThreadHelper.StartNewThread(ConsoleThread, true);
        }
        //重新显示控制台文本
        private bool reShowConsole = false;
        private void ConsoleThread()
        {
            logBLL.Debug("控制台显示线程已启动...");
            while (true)
            {
                if (reShowConsole)
                {
                    ControlDelegateSetProperty(txtConsole, "Text", string.Empty);
                    //重新显示Console内容
                    foreach (Log logTemp in AllLogs)
                    {

                        if (((int)logTemp.LogType & ConfigModel.ConsoleShowType) == (int)logTemp.LogType)
                        {
                            string message = string.Format(txtConsole.Text + "[{0}][{1}][{2}]:{3}\r\n", logTemp.DateTime.ToString("yyyy-MM-dd hh:mm:ss"), logTemp.ClassName, logTemp.LogType.ToString(), logTemp.Message);
                            ControlDelegateSetProperty(txtConsole, "Text", message);
                            ControlDelegateSetProperty(txtConsole, "SelectionStart", txtConsole.Text.Length);
                            ControlDelegateExecuteMethod(txtConsole, "ScrollToCaret");
                        }
                    }
                    reShowConsole = false;
                }
                Log log = null;
                if (logBLL.Dequeue(out log))
                {
                    if (((int)log.LogType & ConfigModel.ConsoleShowType) == (int)log.LogType)
                    {
                        string message = string.Format(txtConsole.Text + "[{0}][{1}][{2}]:{3}\r\n", log.DateTime.ToString("yyyy-MM-dd hh:mm:ss"), log.ClassName, log.LogType.ToString(), log.Message);
                        ControlDelegateSetProperty(txtConsole, "Text", message);
                        ControlDelegateSetProperty(txtConsole, "SelectionStart", txtConsole.Text.Length);
                        ControlDelegateExecuteMethod(txtConsole, "ScrollToCaret");
                    }
                    Application.DoEvents();
                    //将消息写入文件
                    logBLL.WriteFile(log);
                    //保存已处理的消息
                    AllLogs.Add(log);
                }
                Thread.Sleep(20);
            }
        }

        #endregion
    }
}